package com.wheat.coupon.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

/**
 * 创建抽象自定义抽象filter
 *
 * @author wheat on 2019/11/29.
 */
public abstract class AbstractZuulFilter extends ZuulFilter {

    /**
     * 用于过滤器之间传递信息，数据保存在每个请求的ThredLocal中
     */
    RequestContext context;

    private final String NEXT = "next" ;


    @Override
    public boolean shouldFilter() {
        //先获取context，run方法中可以直接使用
        RequestContext context = RequestContext.getCurrentContext();
        return (boolean) context.getOrDefault(NEXT, true);
    }

    @Override
    public Object run() throws ZuulException {
        context = RequestContext.getCurrentContext();
        return cRun();
    }

    protected abstract Object cRun();

    Object fail(int code, String msg) {
        context.set(NEXT, false);
        context.setSendZuulResponse(false);
        context.getResponse().setContentType("text/html;charset=UTF-8");
        context.setResponseStatusCode(code);
        context.setResponseBody(String.format("{\"result\":\"%s!\"}", msg));
        return null;
    }

    Object success() {
        context.set(NEXT, true);
        return null;
    }
}
